import 'package:cave_flutter/model/base_source_model.dart';
import 'package:cave_flutter/model/image_model.dart';
import 'package:cave_flutter/model/other_user_model.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_mine/medal_wall/medal_wall_logic.dart';
import 'package:cave_flutter/pages/whl_mine/privacy_setting/privacy_setting_logic.dart';
import 'package:cave_flutter/utils/whl_current_limiting_util.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../model/dynamic_model.dart';
import '../../../model/user_model.dart';
import '../../../routes/whl_app_pages.dart';

import 'package:cave_flutter/style/whl_style.dart';

class UserInfoLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  late TabController tabController;
  ScrollController scrollController = ScrollController();
  EasyRefreshController refreshController = EasyRefreshController(
      controlFinishLoad: true, controlFinishRefresh: true);
  bool isScrolling = false; //
  bool isShowBar = false; //
  int selectedIndex = 0;

  String accountId = "";
  // String userId = "";
  List listData = [];
  int size = 10;
  int current = 1;

  List<MedalModel> unLockMedal = [];
  UserModel? userModel;
  // OtherUserModel? otherUserModel;
  bool isMine = false;
  bool hide_location = true;
  bool hide_online_time = true;
  bool hide_distance = true;
  bool hide_visit_log = true;
  bool hide_follow = true;
  bool hide_fans = true;
  bool hide_wealth = true;
  bool hide_cave = true;
  bool hide_charm = true;

  @override
  void onInit() {
    super.onInit();
    tabController =
        TabController(length: 3, vsync: this, initialIndex: selectedIndex);
    tabController.addListener(() {
      selectedIndex = tabController.index;
      update();
      if (tabController.index == 0) {
        // getListIn(true);
      } else {
        // getListOut(true);
      }
    });
    scrollController.addListener(() {
      isScrolling = true;
      isShowBar = scrollController.offset > 200.h;
      WhlCurrentLimitingUtil.debounce(() {
        isScrolling = false;
        update();
      });
      update();
    });

    var a = Get.arguments;
    if (a != null) {
      accountId = a["accountId"] ?? "";
      isMine = accountId == WhlUserUtils.getUserInfo().accountId;
      if (!isMine) {
        addVisitLog();
      }
    } else {
      isMine = true;
      accountId = WhlUserUtils.getUserInfo().accountId ?? "";
      // getMyUserInfo();
    }
    getUserDynamicsList(isRefresh: true);
    getUserDetail();
    getMedalInfo();
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }

  getMedalInfo() {
    try {
      WhlApi.getMedalList.get({'accountId': accountId}).then((value) {
        if (value.isSuccess()) {
          unLockMedal = List<MedalModel>.from(
                  value.data['havaList'].map((c) => MedalModel.fromJson(c)))
              .toList();
          update();
        }
      });
    } catch (error) {}
  }

  getUserDetail() {
    try {
      WhlApi.getPersonDetail
          .get({"accountId": accountId}, withLoading: true).then((value) {
        if (value.isSuccess()) {
          userModel = UserModel.fromJson(value.data);
          hide_location = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                        (v) => v.configKey == 'hide_location',
                      )
                      .isOpen ==
                  1;
          hide_online_time = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_online_time')
                      .isOpen ==
                  1;
          hide_distance = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_distance')
                      .isOpen ==
                  1;
          hide_visit_log = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_visit_log')
                      .isOpen ==
                  1;
          hide_follow = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_follow')
                      .isOpen ==
                  1;
          hide_fans = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_fans')
                      .isOpen ==
                  1;
          hide_wealth = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_wealth')
                      .isOpen ==
                  1;
          hide_cave = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_cave')
                      .isOpen ==
                  1;
          hide_charm = !isMine &&
              userModel?.vacies
                      ?.firstWhere(
                          (element) => element.configKey == 'hide_charm')
                      .isOpen ==
                  1;

          update();
        }
      });
    } catch (error) {
      print(error);
    }
  }

  getUserDynamicsList({bool isRefresh = false}) async {
    if (isRefresh) {
      current = 1;
    } else {
      current++;
    }
    Map<String, dynamic> param = {
      "size": size,
      "current": current,
      "accountId": accountId
    };

    ResponseData responseData = await WhlApi.getUserDynamicsList.get(param);
    if (responseData.isSuccess()) {
      List records = responseData.data["records"];
      List<DynamicModel> modelList =
          records.map((e) => DynamicModel.fromJson(e)).toList();
      if (isRefresh) {
        listData = modelList;
        refreshController.finishRefresh();
        refreshController.resetFooter();
      } else {
        listData.addAll(modelList);
        refreshController.finishLoad();
      }
      if (records.length < size) {
        refreshController.finishLoad(IndicatorResult.noMore);
      }
      update();
    } else {
      current--;
      refreshController.finishRefresh();
      refreshController.finishLoad();
      update();
    }
  }

  addVisitLog() {
    WhlApi.addVisit.get({"accountId": accountId}).then((value) {
      if (value.isSuccess()) {
        print("添加访问记录成功");
      }
    });
  }

  attentionRequest() {
    '${WhlApi.userFollow}$accountId'.get({}, withLoading: true).then((value) {
      if (value.isSuccess()) {
        MyToast.show("关注成功");
      }
    });
  }

  Future<void> toEditSquarePage(DynamicModel model) async {
    var a = await Get.toNamed(Routes.publish, arguments: {"model": model});
    if (a != null) {
      getUserDynamicsList(isRefresh: true);
    }
  }

  toEditSoulTag() async {
    var result = await Get.toNamed(Routes.improveInformation,
        arguments: {"isSetter": true});
    if (result != null) {
      getUserDetail();
    }
  }

  toGiftWallPage() async {
    var result =
        await Get.toNamed(Routes.giftWall, arguments: {"isSetter": true});
    if (result != null) {
      getUserDetail();
    }
  }

  toEditUserPage() async {
    var result = await Get.toNamed(Routes.editUserInfo);
    // if (result != null) {
    getUserDetail();
    // }
  }

  toEditDesc() async {
    var result = await Get.toNamed(
      Routes.editDesc,
      arguments: userModel?.aboutMe,
    );
    if (result != null) {
      getUserDetail();
    }
  }

  void bindPhoto(List value) {
    List allUrls = [];
    for (ImageModel element in value) {
      if (element.imageStatus == 1) {
        allUrls.add(element.imageUrl);
      }
    }
    saveUserConfig(otherParam: {
      "uploadUserAlbumBO": {"urls": allUrls}
    });
  }

  saveUserConfig({BaseItemModel? model, Map<String, dynamic>? otherParam}) {
    Map<String, dynamic> param = {model?.requestKey ?? "": model?.requestValue};
    if (otherParam != null) {
      param = otherParam;
    }
    WhlApi.saveUserInformation.post(param, withLoading: true).then((value) {
      if (value.isSuccess()) {
        MyToast.show("保存成功");
        getUserDetail();
      }
    });
  }

  toUnLockMedal() {
    Get.toNamed(Routes.medalWall)?.then((value) {
      getMedalInfo();
    });
  }

  toPublish() async {
    var a = await Get.toNamed(Routes.publish);
    if (a != null) {
      getUserDynamicsList(isRefresh: true);
    }
  }
}
